package com.yaoxuguang.javaDeepAdventure.java_bytecode;

import javax.tools.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;

/**
 * @author yaoxuguang
 * @Title: yao-interview
 * @Package com.yaoxuguang.javaDeepAdventure.java_bytecode
 * @Description: 测试java编译，通过JDK1.8 API
 * @date 2018年12月26日17:09
 */
public class CompileTest {
    public static void main(String[] args) throws URISyntaxException {
        //java源代码
        String source =
                "public class Main{" +
                    "public static void main(String[]args){" +
                        "System.out.println(\"Hello World!\");" +
                    "}" +
                "}";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        StringSourceJavaObject sourceObject = new StringSourceJavaObject("Main", source);
        Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(sourceObject);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null,
                null, null, fileObjects);
        Boolean result = task.call();
        if(result){
            System.out.println("编译成功！");
        }
    }

    static class StringSourceJavaObject extends SimpleJavaFileObject{
        private String content = null;
        public StringSourceJavaObject(String name, String content) throws URISyntaxException {
            super(URI.create("string:///"+name.replace('.','/')+
                Kind.SOURCE.extension), Kind.SOURCE);
            this.content = content;
        }
        public CharSequence getCharSequence(boolean ignoreEncodingErrors) throws IOException{
            return content;
        }
    }
}
